package com.xjwn.datasync.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.toolkit.Db;
import com.xjwn.datasync.CommonResult;
import com.xjwn.datasync.CronTaskRegistrar;
import com.xjwn.datasync.SchedulingRunnable;
import com.xjwn.datasync.Task1;
import com.xjwn.datasync.mapper.DatasyncLogMapper;
import com.xjwn.datasync.mapper.DatasyncMapper;
import com.xjwn.datasync.pojo.Datasync;
import com.xjwn.datasync.pojo.DatasyncLog;
import com.xjwn.datasync.pojo.LogResult;
import com.xjwn.datasync.pojo.ScheduleSetting;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;

@RestController
@Slf4j
@RequestMapping("/api")
public class TaskController {

    @Autowired
    private CronTaskRegistrar cronTaskRegistrar;
    @Autowired
    private DatasyncLogMapper datasyncLogMapper;
    @Autowired
    private DatasyncMapper datasyncMapper;

    /**
     * 添加定时任务
     *
     * @param sysJob
     * @return
     */
    @PostMapping("add")
    public CommonResult<String> add(@RequestBody ScheduleSetting sysJob) {
        sysJob.setCreateTime(LocalDateTime.now());
        sysJob.setUpdateTime(LocalDateTime.now());

        //添加进数据库
        boolean insert = sysJob.insert();
        //根据是否添加成功来判断是否安排任务
        if (!insert) {
            return CommonResult.success("true");
        } else {
            if (sysJob.getJobStatus().equals(1)) {
                // 添加成功,并且状态是1，直接放入任务器
//                SchedulingRunnable task = new SchedulingRunnable(sysJob.getBeanName(), sysJob.getMethodName(),
//                        sysJob.getMethodParams(),sysJob.getSdbUrl(),sysJob.getTdbUrl(),
//                        sysJob.getRemark(), sysJob.getBeginTime(), sysJob.getEndTime(),
//                        sysJob.getProcName(), sysJob.getPkName());
                cronTaskRegistrar.addCronTask(sysJob);
            }
        }
        return CommonResult.success("false");
    }

    /**
     * 修改定时任务
     *
     * @param sysJob
     * @return
     */
    @PostMapping("update")
    public CommonResult<String> update(@RequestBody ScheduleSetting sysJob) {
        sysJob.setCreateTime(LocalDateTime.now());
        sysJob.setUpdateTime(LocalDateTime.now());

        //先查询数据库中是否含有该任务id的任务
        ScheduleSetting one = Db.lambdaQuery(ScheduleSetting.class)
                .eq(ScheduleSetting::getJobId, sysJob.getJobId())
                .one();

        //根据是否更新成功来判断是否含有
        boolean update = Db.saveOrUpdate(sysJob);

        if (!update) {
            return CommonResult.success("true");
        } else {
            // 修改成功,则先删除任务器中原本旧的任务,并重新添加
//            SchedulingRunnable task1 = new SchedulingRunnable(one.getBeanName(), one.getMethodName(),
//                    one.getMethodParams(),one.getSdbUrl(),one.getTdbUrl(), one.getRemark(), one.getBeginTime(),
//                    one.getEndTime(), one.getProcName(), one.getPkName());
            cronTaskRegistrar.removeCronTask(sysJob);
            if (sysJob.getJobStatus().equals(1)) {// 如果修改后的任务状态是1就加入任务器
//                SchedulingRunnable task = new SchedulingRunnable(sysJob.getBeanName(), sysJob.getMethodName(),
//                        sysJob.getMethodParams(),sysJob.getSdbUrl(),sysJob.getTdbUrl(), sysJob.getRemark(),
//                        sysJob.getBeginTime(), sysJob.getEndTime(), sysJob.getProcName(), sysJob.getPkName());
                cronTaskRegistrar.addCronTask(sysJob);
            }
        }
        return CommonResult.success("false");
    }

    /**
     * 删除任务
     *
     * @param jobId
     * @return
     */
    @PostMapping("del/{jobId}")
    public boolean del(@PathVariable("jobId") Integer jobId) {
        // 先查询要删除的任务信息
        ScheduleSetting one = Db.lambdaQuery(ScheduleSetting.class)
                .eq(ScheduleSetting::getJobId, jobId)
                .one();

        boolean del = Db.removeById(one);

        if (!del) {
            System.out.println("任务删除失败");
            return false;

        }
        else {// 删除成功时要清除定时任务器中的对应任务
//            SchedulingRunnable task = new SchedulingRunnable(one.getBeanName(), one.getMethodName(),
//                    one.getMethodParams(),one.getSdbUrl(), one.getTdbUrl(), one.getRemark(), one.getBeginTime(),
//                    one.getEndTime(), one.getProcName(), one.getPkName());
            cronTaskRegistrar.removeCronTask(one);
            System.out.println("任务删除成功");
        }

        return del;
    }

    /**
     * 启动/停止任务
     * @param jobId
     * 任务id
     * @param status
     * 1启动/0停止
     * @return
     * true/false
     */
    // 停止/启动任务
    @PostMapping("changesStatus/{jobId}/{status}")
    public CommonResult<String> changesStatus(@PathVariable("jobId") Integer jobId, @PathVariable("status") Integer status) {
        //更新数据库中任务的状态
        boolean update = Db.lambdaUpdate(ScheduleSetting.class)
                .eq(ScheduleSetting::getJobId, jobId)
                .set(ScheduleSetting::getJobStatus, status)
                .update();
        //没有更新成功则返回false
        if (!update) {
            return CommonResult.success("false");
        }
        // 查询修改后的任务信息
        ScheduleSetting existedSysJob = Db.lambdaQuery(ScheduleSetting.class)
                .eq(ScheduleSetting::getJobId, jobId)
                .one();
        System.out.println("任务信息："+existedSysJob);

        SchedulingRunnable task = new SchedulingRunnable(existedSysJob.getBeanName(), existedSysJob.getMethodName(),
                existedSysJob.getMethodParams(), existedSysJob.getSdbUrl(), existedSysJob.getTdbUrl(), existedSysJob.getRemark(),
                existedSysJob.getBeginTime(), existedSysJob.getEndTime(), existedSysJob.getProcName(), existedSysJob.getPkName(), existedSysJob.getYydm(), existedSysJob.getYymc());
        // 如果状态是1则添加任务
        if (existedSysJob.getJobStatus().equals(1)) {

            System.out.println("开始TASK11"+ task);
            System.out.println("开始前TASK"+ cronTaskRegistrar);
            cronTaskRegistrar.addCronTask(existedSysJob);
            System.out.println("开始后TASK"+ cronTaskRegistrar);
            System.out.println("开启任务");
        } else {
            // 否则清除任务
            System.out.println("停止TASK11"+ task);
            System.out.println("停止前TASK111"+ cronTaskRegistrar);
            cronTaskRegistrar.removeCronTask(existedSysJob);
            System.out.println("停止后TASK222"+ cronTaskRegistrar);
            System.out.println("暂停任务");
        }
        return CommonResult.success("true");
    }


    /**
     * 单次执行任务
     * @param sysJob
     * 任务信息
     * @return
     * true/false
     */
    @PostMapping("once")
    public CommonResult<String> onejob(@RequestBody ScheduleSetting sysJob){
//        SchedulingRunnable task = new SchedulingRunnable(sysJob.getBeanName(), sysJob.getMethodName(), sysJob.getMethodParams(),
//                sysJob.getSdbUrl(), sysJob.getTdbUrl(), sysJob.getRemark(), sysJob.getBeginTime(), sysJob.getEndTime(), sysJob.getProcName(), sysJob.getPkName(),
//                sysJob.getYydm(), sysJob.getYymc());
//        task.run();
        try{
            if (Objects.equals(sysJob.getMethodName(), "SqlServer")){
                Task1 task1 = new Task1();
                task1.SqlServer(sysJob.getMethodParams(),
                        sysJob.getSdbUrl(), sysJob.getTdbUrl(), sysJob.getRemark(), sysJob.getBeginTime(), sysJob.getEndTime(), sysJob.getProcName(), sysJob.getPkName(),
                        sysJob.getYydm(), sysJob.getYymc(),"true");
                return CommonResult.success("true");
            }else {
                Task1 task1 = new Task1();
                task1.Oracle(sysJob.getMethodParams(),
                        sysJob.getSdbUrl(), sysJob.getTdbUrl(), sysJob.getRemark(), sysJob.getBeginTime(), sysJob.getEndTime(), sysJob.getProcName(), sysJob.getPkName(),
                        sysJob.getYydm(), sysJob.getYymc(),"true");
                return CommonResult.success("true");
            }
        } catch (Exception e) {
//            throw new RuntimeException(e);
            return CommonResult.error(0,e.toString());
        }


    }


    /**
     * 获取任务列表
     * @param id
     * 任务ID，0查全部
     * @return
     * 任务列表ScheduleSetting
     */
    @PostMapping("getjob/{id}")
    public CommonResult< List<ScheduleSetting>> getjob(@PathVariable("id") Integer id){

        if(id==0){
            List<ScheduleSetting> jobList = Db.lambdaQuery(ScheduleSetting.class)
                    .list();
            return  CommonResult.success(jobList);
        }
        else {
            List<ScheduleSetting> jobList = Db.lambdaQuery(ScheduleSetting.class)
                    .eq(ScheduleSetting::getJobId,id)
                    .list();
            return  CommonResult.success( jobList);
        }

    }

    /**
     * 获取任务日志
     * @param param 目标表名
     * @param pkname 主键名
     * @return 日志列表
     */
    @PostMapping("getlog/{param}/{pkname}")
    public CommonResult<List<DatasyncLog>> getlog(@PathVariable("param") String param,@PathVariable("pkname") String pkname){

        int pageNum=1;
        int pageSize=20;

//        Page<DatasyncLog> page = new Page<>(pageNum,pageSize);
//        IPage<DatasyncLog> iPage = datasyncLogMapper.selectUserPage(page,param);
//        System.out.println(iPage);



        if(Objects.equals(pkname, "0")){
            List<DatasyncLog> logList = Db.lambdaQuery(DatasyncLog.class)
                    .list();
            return CommonResult.success(logList);
        }
        else {
            List<DatasyncLog> logList = Db.lambdaQuery(DatasyncLog.class)
                    .eq(DatasyncLog::getParams,param)
//                    .eq(DatasyncLog::getPkname,pkname)
                    .list();
            return CommonResult.success(logList);
        }

    }


    /**
     * 分页获取日志信息
     * @param current 查询第几页
     * @param size 每页数据量
     * @param str 查询条件
     * @return 返回page
     */
    @PostMapping("getlog/ByPage")
    public CommonResult<LogResult> getUsersByPage(int current, int size, String params) {
        if (params==null)
        {
            params="";
        }
//        Page<Datasync> page = new Page<>(current, size);
//        QueryWrapper<Datasync> wrapper = new QueryWrapper<>();
//        wrapper.orderByDesc("time")
//                .like("params",params);
//
//        return CommonResult.success(datasyncMapper.selectPage(page, wrapper)); // 第二个参数为查询条件（Wrapper）

        //region 分页
        Integer int1 = ((current-1)*size)+1;
        Integer int2 = ((current-1)*size)+size;

        LogResult logResult = new LogResult();
        logResult.setRecords(datasyncMapper.selectUserPage(params,int1,int2));
        logResult.setTotal(Integer.parseInt(datasyncMapper.selectUserCont(params).getFirst()));
        Integer pages= (logResult.getTotal()+size-1)/size;
        logResult.setPages(pages);
        logResult.setCurrent(current);
        logResult.setSize(size);
        return CommonResult.success(logResult);
        //endregion
    }

    /**
     * 分页获取日志信息
     * @param current 查询第几页
     * @param size 每页数据量
     * @param params 目标表名
     * @param uuid uuid
     * @return 返回page
     */
    @PostMapping("getlogmx/ByPage")
    public CommonResult<LogResult> getUsersByPage(int current,int size,String params,String uuid) {
        if (params==null)
        {
            params="";
        }
        if (uuid==null){
            uuid="";
        }

//        QueryWrapper<DatasyncLog> wrapper = new QueryWrapper<>();
//        wrapper.orderByDesc("time")
//                .like("params",params)
//                .like("uuid",uuid);
//        LogResult logResult =new LogResult().records()
//        return CommonResult.success((Page<DatasyncLog>) datasyncLogMapper.selectUserPage(params,uuid,10,20));
//        return CommonResult.success(datasyncLogMapper.selectPage(page, wrapper)); // 第二个参数为查询条件（Wrapper）

        //region 分页
        Integer int1 = ((current-1)*size)+1;
        Integer int2 = ((current-1)*size)+size;

        LogResult logResult = new LogResult();
        logResult.setRecords(datasyncLogMapper.selectUserPage(params,uuid,int1,int2));
        logResult.setTotal(Integer.parseInt(datasyncLogMapper.selectUserCont(params,uuid).getFirst()));
        Integer pages= (logResult.getTotal()+size-1)/size;
        logResult.setPages(pages);
        logResult.setCurrent(current);
        logResult.setSize(size);
        return CommonResult.success(logResult);
        //endregion

    }

}


